//
//  NetworkTools.swift
//  GeneralNetworkTool
//
//  Created by Jin on 2018/5/23.
//  Copyright © 2018年 Jin. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType {
    case GET
    case POST
}

class NetworkTools: AFHTTPSessionManager {
    
    static let shareInstance:NetworkTools = {
        let instance = NetworkTools(baseURL: nil, sessionConfiguration: URLSessionConfiguration.default)
        return instance
    }()
}

//封装请求方法
extension NetworkTools {
    
    //登录
    func userLogin(request:UserLoginRequest,finished:@escaping (_ result:Any?,_ error:Error?)->Void) {
        let data = try? JSONEncoder().encode(request)
        doHTTPSPOST(requestUrlStr: "http://www.baidu.com", parameters: nil, body: data!) { (objc, error) in
            if let objc = objc {
                finished(objc,nil)
            }else {
                finished(nil,error)
            }
        }
    }
}


//私有方法
extension NetworkTools {
    private func doHTTPSPOST(requestUrlStr:String,parameters:[String:AnyObject]?,body:Data,finished:@escaping (_ result:Any?,_ error:Error?)->Void) {
        
        let url = URL(string: requestUrlStr)
        var request = URLRequest(url: url!)
        request.httpBody = body
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        
        let manager = AFHTTPSessionManager()
        manager.requestSerializer.timeoutInterval = 50
        manager.responseSerializer = AFHTTPResponseSerializer.init()
        manager.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/plain","text/html") as? Set<String>
        let securityPolicy = AFSecurityPolicy(pinningMode: .none)
        securityPolicy.allowInvalidCertificates = true
        securityPolicy.validatesDomainName = false
        manager.securityPolicy = securityPolicy
        let task:URLSessionDataTask = manager.dataTask(with: request) { (response, objc, error) in
            if let error = error {
                finished(nil,error)
            }else {
                finished(objc,nil)
            }
        }
        task.resume()
    }
}
